package util

import (
	"bytes"
	"encoding/base64"
	"golang.org/x/text/encoding/simplifiedchinese"
	"image"
	"image/jpeg"
)

// DecodeToGBK GBK转UTF-8
func DecodeToGBK(text string) (string, error) {

	dst := make([]byte, len(text)*2)
	tr := simplifiedchinese.GB18030.NewDecoder()
	nDst, _, err := tr.Transform(dst, []byte(text), true)
	if err != nil {
		return text, err
	}
	return string(dst[:nDst]), nil
}

// ImageToBase64 图片转base64
func ImageToBase64(image image.Image) (string, error) {
	emptyBuff := bytes.NewBuffer(nil)
	err := jpeg.Encode(emptyBuff, image, nil)
	if err != nil {
		return "", err
	}
	dist := make([]byte, 50000)
	base64.StdEncoding.Encode(dist, emptyBuff.Bytes())
	index := bytes.IndexByte(dist, 0)
	baseImage := dist[0:index]
	return "data:image/png;base64," + string(baseImage), nil
}
